package com.study.manage.mvc.org.channel;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.study.manage.dal.EvaluateApplyRepository;
import com.study.manage.dal.OrderRepository;
import com.study.manage.utils.DateTimeUtil;

@Service
public class CheckEvaluateInfoService {

	@Autowired
	private EvaluateApplyRepository evaluateApplyRepository;
	@Autowired
	private OrderRepository orderRepository;

	public Map<String, Object> getBaseData(Long id, Long referenceId) {

		Date date = new Date();
		List<Long> ids = Arrays.asList(id);
		Map<String, Object> map = new HashMap<>();
		map.put("successCount", evaluateApplyRepository.countSuccessByEvaluateId(id, null,referenceId));
		map.put("successCountDay", evaluateApplyRepository.countSuccessByEvaluateId(id, date,referenceId));
		Float orderSum = orderRepository.sumPriceByReferenceId(ids,null,referenceId);
		Float orderSumDay = orderRepository.sumPriceByReferenceId(ids, date,referenceId);
		map.put("orderSum", orderSum == null ? 0 : orderSum);
		map.put("orderSumDay", orderSumDay == null ? 0 : orderSumDay);
		map.put("id", id);
		return map;
	}

	public List<Map<String, Object>> getReturnList(Date beginAt, Date endAt, List<Object[]> objs) {

		List<Map<String, Object>> list = new ArrayList<>();
		Calendar cal = Calendar.getInstance();
		cal.setTime(beginAt);
		while (cal.getTime().getTime() <= endAt.getTime()) {
			String nowDate = DateTimeUtil.format(cal.getTime(), DateTimeUtil.DATE_PATTERN_SHORT);
			Map<String, Object> map = new HashMap<>();
			for (Object[] os : objs) {
				Timestamp time = (Timestamp) os[0];
				String nTime = DateTimeUtil.format(new Date(time.getTime()), DateTimeUtil.DATE_PATTERN_SHORT);
				if (nTime.equals(nowDate)) {
					map.put(os[2].toString(), os[1]);
				}
			}
			map.put("date", nowDate + "(" + DateTimeUtil.getDaysInWeek(cal.getTime()) + ")");
			list.add(map);
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		Collections.sort(list, new Comparator<Map<String, Object>>() {
			public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
				return ((String) arg1.get("date")).compareTo(((String) arg0.get("date")));
			}
		});
		return list;
	}

}
